package hr.fer.zpr.nmbp.project1.dao;

import hr.fer.zpr.nmbp.project1.dao.exceptions.PrimaryKeyConstraintException;
import hr.fer.zpr.nmbp.project1.model.Karton;

import java.util.List;

import com.db4o.ObjectContainer;
import com.db4o.constraints.UniqueFieldValueConstraintViolationException;

public class KartonDAO {

	private ObjectContainer db;
	
	public KartonDAO(ObjectContainer db) {
		this.db = db;
	}
	
	public void save(Karton karton) {
		
		if(karton.getPacijent() == null){
			throw new PrimaryKeyConstraintException("Karton mora imati dodijeljenog pacijenta");
		}
		
    	this.db.store(karton);
		
		try{
			this.db.commit();
		}catch(UniqueFieldValueConstraintViolationException e){
			this.db.rollback();
			throw new PrimaryKeyConstraintException("Karton za pacijenta već postoji u bazi podataka");
		}
    }
        

    public List<Karton> load(Karton kartonPrototype) {
        return db.queryByExample(kartonPrototype);
    }
    
    public List<Karton> loadAll() {
        return db.query(Karton.class);
    }

}
